package timbap.visualizer.api.plugin.container;

import timbap.visualizer.api.model.TimeCode;

/**
 * The <code>AbstractTransitionModeController</code> provides a common base
 * implementation for mode controllers that automatically publish a
 * switch command to the next mode, as soon as the keep alive signal
 * has expired and a command to the previous mode, as soon as a keep alive
 * signal is received.
 *
 * @author  Andreas Pabst
 * @see     timbap.visualizer.api.plugin.container.AbstractKeepAliveModeController
 * @see     timbap.visualizer.api.plugin.container.KeepAliveModeController
 */
public abstract class AbstractTransitionModeController extends AbstractKeepAliveModeController {

    private static final float MOVEMENT_DETECTION_THRESHOLD = 0.1f;

    boolean activationKeepAliveSent = false;

    @Override
    public void activate() {
        activationKeepAliveSent = false;
        super.activate();
    }

    @Override
    public void keepAlive() {
        if (isKeepAliveAccepted()) {
            activationKeepAliveSent = false;
            publishPluginSwitchCommand(PluginSwitchCommand.PREVIOUS);
        } else {
            activationKeepAliveSent = true;
            super.keepAlive();
        }
    }

    @Override
    public boolean isKeepAliveAccepted() {
        return activationKeepAliveSent;
    }

    public boolean isReturnActionDetected() {
        return getTimeCode().getSignalPower() > MOVEMENT_DETECTION_THRESHOLD;
    }
    
    @Override
    public void timeCodeUpdated(TimeCode pTimeCode) {
        super.timeCodeUpdated(pTimeCode);
        if (isReturnActionDetected()) {
            keepAlive();
        }
    }


}